﻿using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint.WebControls;
using System.Web.UI.WebControls;
using System.Web.Security;
using EAT.Common;
using System.Configuration;
using System.DirectoryServices;
using Microsoft.SharePoint;
using Microsoft.Office.Server.UserProfiles;
using Microsoft.Office.Server;

namespace ECTSUserMgmtExtension
{
    public class UserInfoPage : LayoutsPageBase
    {
        //
        // The following text boxes display information about the user
        // loaded (and saved to) ADAM.
        //
        protected TextBox tbFirstName;
        protected TextBox tbLastName;
        protected TextBox tbServiceName;
        protected TextBox tbTelephoneNumber;
        protected TextBox tbDisplayName;
        protected Label lblAccountName;

        //
        // This textbox recieves the user's password.  This is validated
        // to unlock further profile update options.
        //
        protected TextBox tbPassword;

        //
        // Radio buttons to select password modification and secret q/a update.
        //
        protected CheckBox cbChangePassword;
        protected TextBox tbNewPassword;
        protected TextBox tbConfirmPassword;

        protected CheckBox cbChangeQA;
        protected TextBox tbQuestion;
        protected TextBox tbAnswer;

        protected Label lblInternalCaller;
        //
        // Button to submit changes to ADAM.
        //
        protected Button btnUpdate;
        protected Label lblDebug;

        private cUserManager m_UM;

        public UserInfoPage()
        {
            m_UM = new cUserManager(
                ConfigurationManager.ConnectionStrings["ADAMConnectionString"].ConnectionString
                );
        }

        protected override void OnLoad(EventArgs e)
        {
            MembershipUser Mu;
            try
            {
                Mu = System.Web.Security.Membership.GetUser();
            }
            catch
            {
                return;
            }

            lblAccountName.Text = String.Format("Account Name: {0}", Mu.Email);

            if (!Page.IsPostBack)
            {
                tbServiceName.Text = m_UM.GetUserAttribute(Mu, "company");
                tbFirstName.Text = m_UM.GetUserAttribute(Mu, "givenName");
                tbLastName.Text = m_UM.GetUserAttribute(Mu, "sn");
                tbDisplayName.Text = m_UM.GetUserAttribute(Mu, "displayName");
                if (tbDisplayName.Text == "")
                    tbDisplayName.Text = m_UM.GetUserAttribute(Mu, "mail");

                tbTelephoneNumber.Text = m_UM.GetUserAttribute(Mu, "telephoneNumber");
                tbQuestion.Text = m_UM.GetUserAttribute(Mu, "eatmuPasswordQuestion");

                cbChangePassword.Enabled = true;
                cbChangePassword.Checked = false;

                cbChangeQA.Enabled = true;
                cbChangeQA.Checked = false;
            }
        }

        protected void btnUpdate_Click(object sender, EventArgs e)
        {
            MembershipUser u = System.Web.Security.Membership.GetUser();
            lblDebug.Text = "";

            try
            {
                if (cbChangeQA.Checked == true)
                {
                    cbChangeQA.Checked = false;
                    if (u.ChangePasswordQuestionAndAnswer(tbPassword.Text, tbQuestion.Text, tbAnswer.Text) == false)
                    {
                        lblDebug.Text += "Attempt to update password question and answer failed";
                    }
                    else
                    {
                        lblDebug.Text += "Password Question and Answer updated successfully" + "<br>";
                    }
                }

                if (cbChangePassword.Checked == true)
                {
                    cbChangePassword.Checked = false;

                    // this is somewhat redundant as the ChangePassword below will validate
                    // the user's password as well. This does provide a better error message,
                    // however, so I'm leaving it here.
                    if (System.Web.Security.Membership.ValidateUser(u.UserName, tbPassword.Text) == false)
                    {
                        throw new Exception("Password provided does not match your current password");
                    }

                    if (tbNewPassword.Text != tbConfirmPassword.Text)
                    {
                        throw new Exception("The new passwords to not match");
                    }

                    try
                    {
                        //m_UM.ChangePassword(u, tbPassword.Text, tbNewPassword.Text);
                        u.ChangePassword(tbPassword.Text, tbNewPassword.Text);
                        lblDebug.Text += "Password has been updated." + "<br>";
                    }
                    catch
                    {

                        try
                        {
                            SPSecurity.RunWithElevatedPrivileges(
                                delegate()
                                {
                                    DirectoryEntry user = m_UM.FindUser(u.UserName);
                                    user.Options.PasswordPort = m_UM.Connection.Port();
                                    user.Invoke("ChangePassword", new object[] { tbPassword.Text, tbNewPassword.Text });
                                    user.CommitChanges();
                                }
                            );
                        }
                        catch (System.Reflection.TargetInvocationException)
                        {
                            throw new Exception("Error occured while trying to set the password");
                        }
                    }
                }

                if (tbServiceName.Text == "")
                {
                    throw new Exception("You must provide a Service Name");
                }
                if (tbFirstName.Text == "")
                {
                    throw new Exception("You must provide a First Name");
                }
                if (tbLastName.Text == "")
                {
                    throw new Exception("You must provide a Last Name");
                }
                if (tbTelephoneNumber.Text == "")
                {
                    throw new Exception("You must provide a Telephone Number");
                }
                if (tbDisplayName.Text == "")
                {
                    throw new Exception("You must provide a Display Name");
                }

                SPSecurity.RunWithElevatedPrivileges(
                    delegate()
                    {
                        DirectoryEntry user = m_UM.FindUser(u.UserName);
                        if (user == null)
                            throw new Exception("User Manager failed to find user " + u.UserName);

                        user.Properties["company"].Value = tbServiceName.Text;
                        user.Properties["givenName"].Value = tbFirstName.Text;
                        user.Properties["SN"].Value = tbLastName.Text;
                        user.Properties["displayName"].Value = tbDisplayName.Text;
                        user.Properties["telephoneNumber"].Value = tbTelephoneNumber.Text;
                        user.CommitChanges();
                    }
                );

                lblDebug.Text += "User information has been updated successfully" + "<br>";
            }
            catch (Exception Ex)
            {
                lblDebug.Text = Ex.Message;
            }
        }
    }
}
